package com.hsd.voice_asr.socket;

import com.hsd.voice_asr.utils.SocketUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.time.LocalDateTime;

@Slf4j
public class SocketControlThread extends Thread {

    private SocketChannel socketChannel;

    private String deviceKey = "";

    public SocketControlThread(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    public void run() {
        try {
            initDeviceKey();
            log.info("client socketControlThread connected {}",deviceKey);
            socketChannel.configureBlocking(false);
            SocketUtil.startMeeting(deviceKey);
            boolean flag = true;
            while (flag) {
                SocketUtil.sendMessage(socketChannel, "ACKSTART||PING||ACKEND");
                ByteBuffer byteBuffer = ByteBuffer.allocate("ACKSTART||PONG||ACKEND".getBytes().length);
                int length = 0;
                LocalDateTime now = LocalDateTime.now();
                while (length == 0) {
                    if (now.plusSeconds(500).isBefore(LocalDateTime.now())) {
                        flag = false;
                        break;
                    } else {
                        length = socketChannel.read(byteBuffer);
                    }
                    Thread.sleep(2000);
                }
            }
        } catch (Exception e) {
        }finally {
            log.error("client socketControlThread inputStream close");
            SocketUtil.removeSocketChannel(deviceKey);
        }
    }

    private void initDeviceKey() throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1);
        while (true) {
            byteBuffer.clear();
            socketChannel.read(byteBuffer);
            byteBuffer.flip();
            deviceKey += new String(byteBuffer.array());
            if (deviceKey.indexOf("ACKEND") != -1) {
                deviceKey = deviceKey.substring(10, deviceKey.indexOf("||ACKEND")).trim();
                SocketUtil.addSocketControl(deviceKey,socketChannel);
                break;
            }
        }
    }

}
